import {NextResponse} from "next/server"
import { db } from "@/lib/db"

export async function GET(request) {
    const sql = "select * from users";

    try {
        const results = await new Promise((resolve, reject) => {
            db.query(sql, (err, results) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(results);
                }
            });
        });

        return NextResponse.json({ data: results });
    } catch (error) {
        return NextResponse.json({ msg: "查询失败" }, { status: "500" });
    }
}

export async function POST(request){
    // const formData = await request.formData()
    // const username = formData.get('username')
    // const password = formData.get('password')

    const res = await request.json()
    const sql = `INSERT INTO users (username, password) VALUES ('${res.username}', '${res.password}')`;
    
    try {
        await new Promise((resolve, reject) => {
            db.query(sql, (err, results) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(results);
                }
            });
        });

        return NextResponse.json({ msg: "添加成功" });
    } catch (error) {
        return NextResponse.json({ msg: "添加失败" }, { status: "500" });
    }
}

